/**
 * User: zhangqiang
 * Date: 15-8-11
 * Time: 上午11:04
 * 查询面板
 */

define(["require",
		"dojo/_base/declare",
		"dojo/_base/lang",
		"dojo/_base/array",
		"dojo/_base/fx",
		"dojo/fx/easing",
		"../../util/ajaxUtil",
		"dojo/dom",
		"dojo/dom-attr",
		"dojo/dom-class",
		"dojo/dom-style",
		"dojo/on",
		"dojo/query",
		"esri/tasks/query",
		"esri/tasks/QueryTask",
		"dojo/topic",
		"../BaseWidget",
		"esri/graphic",
		"dojo/dom-construct",
		"dijit/form/Button",
		"esri/Color",
		"gistech/widgets/menubarWidget/layerLable",
		"gistech/widgets/LandExpandEdit/LandExpandEdit",
		"gistech/widgets/LandManageAndControlReportWidget/LandManageAndControlReportWidget",
		"gistech/widgets/drawGeometryWidget/DrawGeometryWidget","esri/layers/ArcGISTiledMapServiceLayer",
		"gistech/widgets/SpecialDataReportWidget/SpecialDataReportWidget","esri/geometry/Point",
		"esri/layers/FeatureLayer","esri/layers/ArcGISDynamicMapServiceLayer","esri/InfoTemplate",
		"esri/layers/GraphicsLayer", "esri/symbols/PictureMarkerSymbol","esri/symbols/SimpleLineSymbol",
		"dijit/layout/ContentPane","gistech/widgets/FeatureInfoDialog/FeatureInfoDialog","dojo/text!./templates/Template.html"],
    function (require, declare, lang, array, baseFx,easing,ajaxUtil, dom, domAttr, domClass, domStyle, on, query,Tquery,QueryTask,topic, 
    		BaseWidget,Graphic,domConstruct,Button,Color,LayerLable,LandExpandEdit,LandManageAndControlReportWidget,DrawGeometryWidget,ArcGISTiledMapServiceLayer,SpecialDataReportWidget,
    		Point,FeatureLayer,ArcGISDynamicMapServiceLayer,InfoTemplate,GraphicsLayer,PictureMarkerSymbol,SimpleLineSymbol,ContentPane,FeatureInfoDialog,template) {
        return declare([BaseWidget], {
        	templateString: template,
            map: null,
            resourceTreeData:null,
            lefttabCon:null,
            treenode:null,
            layerCount:0,
            highLightLayer:null,
            landExpandEdit:null,
            landExpandLayer:null,
            showLayTreeParents:null,
            showTreeObj:null,
            featureDialog:null,
            constructor: function (args) {
                this.map = args.map;
                this.lefttabCon  = args.lefttabCon;
                window.MapLayerResourceWidget=this;//这个是用在弹出信息模板框的时候用到
            },
            postCreate: function () {
            	this.inherited(arguments);
            },
            startup: function () {
                this.inherited(arguments);
                this.init();
            },
            init:function(){
            	this.treenode = [];
            	this.resourceTreeData=jQuery.parseJSON(ioc.map.userRoleResource);
            	this.getDataThemetree();
            	this.addEvents();
            	this.highLightLayer=new GraphicsLayer({id:"highLightLayer"});
            	this.map.addLayer(this.highLightLayer);
            },
            getDataThemetree:function(){
            	ajaxUtil.request("../client/backgroundManagement/DataThemeController/tree","",lang.hitch(this,function(results){
            		dojo.forEach(results,lang.hitch(this,function(tree,index){//19个对象
            			tree.isValid=false;
            			dojo.forEach(this.resourceTreeData,function(resObj,ind){
            				if(resObj.RESOURCE_ID==tree.id||tree.id==resObj.RESOURCE_PARENT_ID){
            					tree.isValid=true;}
            			})
            		}))
            		dojo.forEach(results,function(item,index){
            			dojo.forEach(results,function(temp,ind){
            				if(item.id==temp.pid&&temp.isValid==true){
            					item.isValid=true}
            			});
            		});
            		var realTreeNode=dojo.filter(results,function(item,index){
            			return item.isValid==true;
            		})
            		dojo.forEach(realTreeNode,lang.hitch(this,function(item,index){
            			item.layerObj=null;
            			dojo.forEach(this.resourceTreeData,function(obj,ind){
            				if(item.id==obj.RESOURCE_ID){
            					item.layerObj=obj;}
            			})
            		}))
            		this.ShowResourceLis(realTreeNode);//加载资源树
            	}));
            },
            
            queryByLocation:function(e){
            	debugger
            	this.results=[];
            	if(e.graphic._graphicsLayer.fields){
            		this.results.push({"fields":e.graphic._graphicsLayer.fields,"features":e.graphic,layerid:e.graphic._graphicsLayer.id});
            	}else{
            		this.results.push({"fields":e.graphic.fields,"features":e.graphic,layerurl:null,layerid:null});
            	}
            	this.createInfoDialog(this.results);
            },
            createInfoDialog:function(res){
            	debugger
            	if(this.featureDialog&&dijit.byId("feaInfoTemplate")){
        			this.featureDialog.reCreateTable({"feaSet":res});
        		}else{
        			debugger
        			var activeMap=dojo.filter(Global.maps,function(item){if(Global.activeMapId==""||Global.activeMapId=="map"){return this.map;}else{return item.id==Global.activeMapId;}})[0];
            		if(activeMap==undefined){activeMap=this.map;}
        			this.featureDialog=new FeatureInfoDialog({"feaSet":res,id:"feaInfoTemplate",map:activeMap});
                	this.featureDialog.startup();
            	}
            },
            addEvents:function(){
            	topic.subscribe("graphicClickEvent",lang.hitch(this,function(e){
            		this.queryByLocation(e);
            	}));
            	//监听地图点击事件，调用同一的弹窗显示信息。
            	topic.subscribe("LandExpandEditWidgetDestroy",function(){
            		this.landExpandEdit=null;
            	});
            	on(this.map,"zoom-end",lang.hitch(this,function(){
            		this.dyAndFeaChange();
            	}));
            	topic.subscribe("isHadLoadLayerEvent",lang.hitch(this,function(e){
            		this.isHadLoadLayerEvent(e);
            	}));
            },
            //判断图层是否已加载，未加载则提示
            isHadLoadLayerEvent:function(layernm){
            	var hadLoadLayers=[];
            	dojo.forEach(Global.mapshasaddlayers[Global.activeMapId],function(item,index){
            		hadLoadLayers.push(item.text)});
            	if($.inArray(layernm,hadLoadLayers)==-1){
            		layer.msg(layernm+"图层未添加",{icon:2});return false;
            	}
            },
            //图层加载异常时，节点变颜色，并弹框提示
            layerLoadError:function(layerid){
            	dojo.forEach(Global.mapshasaddlayers[Global.activeMapId],function(item,index){
            		if(item.layerObj&&item.layerObj.RESOURCE_ID==layerid.split("#")[0]){
            			domStyle.set(dojo.byId(item.tId+"_a"),"color","#f00");
            			layer.msg(item.layerObj.RESOURCE_NAME+"图层加载失败，服务地址访问异常！", {
    						icon : 2,time:3000
    					});
            		}
            	});
            },
            dyAndFeaChange:function(){
            	this.mainMapDyAndFeaChange();
            	this.assistantMapDyAndFeaChange();
            },
            assistantMapDyAndFeaChange:function(){
            	debugger
            	if(Global.maps.length>1){
            		dojo.forEach(Global.maps,lang.hitch(this,function(item,index){
            			if(item.id!="map"){
            			  dojo.forEach(Global.mapshasaddlayers[item.id],lang.hitch(this,function(it,ind){
            				  if(this.map.getLevel()>=parseInt(it.layerObj.CHANGELEVEL)){
            					  item.getLayer(it.id+"#M").hide();
            					  item.getLayer(it.id+"#F").show(); 
            				  }else{
            					  item.getLayer(it.id+"#F").hide();
            					  item.getLayer(it.id+"#M").show();
            				  }
             			  }));
            			  
            			}
            		}))
            	}
            },
            mainMapDyAndFeaChange:function(){
        		var maplevel = this.map.getLevel();
            	dojo.forEach(Global.mapshasaddlayers[Global.activeMapId],lang.hitch(this,function(item,index){
                   debugger
            		if(maplevel>=parseInt(item.layerObj.CHANGELEVEL)){
            			this.map.getLayer(item.id+"#M").hide();
            			this.map.getLayer(item.id+"#F").show();
            		}else{
            			this.map.getLayer(item.id+"#M").show();
            			this.map.getLayer(item.id+"#F").hide();
            		}
            	}));
            },
            reOrderLayer:function(){
            	try{
            		var treeLayerCount=Global.mapshasaddlayers[Global.activeMapId].length;//3个
                	var layerOrder=Global.mapshasaddlayers[Global.activeMapId];//目前加载的图层的顺序，序号小的在上层
                	debugger
                	dojo.forEach(layerOrder,lang.hitch(this,function(item,index){
                			this.map.reorderLayer(this.map.getLayer(item.id+"#F"),treeLayerCount-index);
                			this.map.reorderLayer(this.map.getLayer(item.id+"#M"),treeLayerCount-index);          		
                	}))
                	this.map.reorderLayer(this.map.getLayer("highLightLayer"),2*treeLayerCount+1);
            	}catch (e) {
					console.log(e);
				}finally{
					
				}
            },
            //设置图层显隐性。
            showOptialSet:function(event, treeId, treeNode){
            	var dyLayer=this.map.getLayer(treeNode.id+"#M");
            	var feLayer=this.map.getLayer(treeNode.id+"#F");
            	var opcitalF=feLayer.opacity*10;
            	opcitalStr="<input type='range' min='0' max='10'  step='1' value='"+opcitalF+"'  id='"+treeNode.id+"'>"
            	artDialog({id:treeNode.id,title:treeNode.text+'图层设置',content:opcitalStr,lock:false, style:'succeed noClose',noText:null,},function(){},function(){});
            	var range=dojo.byId(treeNode.id);
            	on(range,"mouseup",lang.hitch(this,this.setOptail));
            },
            setOptail:function(evt){
            	var dyLayer=this.map.getLayer(evt.target.id+"#M");
            	dyLayer.setOpacity(parseInt(evt.target.value)/10);
            	var feLayer=this.map.getLayer(evt.target.id+"#F");
            	feLayer.setOpacity(parseInt(evt.target.value)/10);
            },
            //拖动控制
            stopToAnotherFu:function(treeId, treeNodes, targetNode, moveType){
            	if(targetNode==null){return false;}else{return !(targetNode==null||moveType=="inner"||targetNode.pid==null||targetNode.pid!=this.showLayTreeParents.id);}
            },
            //加载图层树
    		ShowResourceLis:function(treeNode) {
    				var ztreeSetting = { 
    				    check: { enable : false},
    					data:{simpleData:{enable: true,idKey: "id",pIdKey: "pid",rootPId: 0},key:{name:"text"}},
    					callback: 
    					    { onClick: lang.hitch(this,this.xxTreeNodeClick)},
    					view:{showIcon:true,txtSelectedEnable: true},
    					edit: {
    						enable: true,
    						drag: {isCopy: false,isMove:false ,prev: true,next: true,inner: false},
    						showRemoveBtn: false,
    						showRenameBtn: false
    					}};	
    				$.fn.zTree.init($("#resourcetree"), ztreeSetting, treeNode);
    				var treeObj = $.fn.zTree.getZTreeObj("resourcetree");
    				treeObj.expandAll(true);
    				var shwoTreeNode=[{id:"root",pid:null,text:"已加载图层"}];
				    var showTreeSetting = { 
	    				    check: { enable : false,},
	    					data:{simpleData:{enable: true,idKey: "id",pIdKey: "pid",rootPId: 0},key:{name:"text"}},
	    					callback: {
	    						  onClick: lang.hitch(this,this.showOptialSet),
	    						  beforeDrop:lang.hitch(this,this.stopToAnotherFu),
	    						  onDrop: lang.hitch(this,this.reOrderLayer),
	    						  onRemove:lang.hitch(this,this.removeLayer)},
	    					view:{showIcon:true,txtSelectedEnable: true},
	    					edit: {
	    						enable: true,
	    						drag: {isCopy: false,isMove: true,prev: true,next: true,inner: false},
	    						showRemoveBtn: true,
	    						showRenameBtn: false
	    					}};
				  $.fn.zTree.init($("#resourceShowedLayerTree"), showTreeSetting, shwoTreeNode);
				  this.showTreeObj = $.fn.zTree.getZTreeObj("resourceShowedLayerTree");
				  this.showLayTreeParents=this.showTreeObj.getNodeByParam("id","root");
				  $("#resourceShowedLayerTree").css("display","none");
    		},
    		xxTreeNodeClick:function(event, treeId, treeNode){
    			debugger;
    			  var showTreeReIds=[];
    			  dojo.forEach(Global.mapshasaddlayers[Global.activeMapId],function(item,index){
    				  showTreeReIds.push(item.id)})
    			  if(treeNode.layerObj==null){
    				  return false;
    			  }else if($.inArray(treeNode.id,showTreeReIds)!=-1){//&&Global.activeMapId=='map'
    				  layer.msg("图层已经添加",{icon:2});return false;
    			  }else{
    				  this.addLayersToMap(treeNode.layerObj);
    				  this.addLayerLableToActiveMapView(treeNode);
    			  }},
    		addLayerLableToActiveMapView:function(treeNode){
    			debugger
    			var activeMap=null;
    			if(Global.maps&&Global.maps.length>0){
    				activeMap = Global.maps.filter(function(item){
    					return item.id==Global.activeMapId;
    				})[0];
    			}else{
    				activeMap = this.map;
    				Global.activeMapId = "map";
    			}
    			
    			if(Global.mapshasaddlayers.hasOwnProperty(Global.activeMapId)){
    				Global.mapshasaddlayers[Global.activeMapId].push(treeNode);
    			}else{
    				Global.mapshasaddlayers[Global.activeMapId] = [treeNode];
    			}
    			if(dijit.byId(activeMap.id)){
    				dijit.byId(activeMap.id).addLable(treeNode);
    			}else{
    				var layerLable=new LayerLable({id:activeMap.id,mid:Global.activeMapId,map:activeMap,treeNode:treeNode});
    				if(Global.activeMapId=="map"){Global.widgets.mainMapLayerLabel=layerLable};
//    				if(Global.activeMapId=="map3"&&Global.maps.length==4){Global.widgets.leftMapLayerLabel=layerLable};
        			layerLable.startup();
        			debugger
        			//layerLable.addLable(treeNode);
    			}
    		},
			addLayerLableToShowedTab:function(treeNode){
				  $("#resourceShowedLayerTree").css("display","block");
				  this.showTreeObj.addNodes(this.showLayTreeParents,treeNode);
				  this.showTreeObj.moveNode(this.showLayTreeParents.children[0],this.showLayTreeParents.children[this.showLayTreeParents.children.length-1],"prev");
			  },
			removeLayer:function(event, treeId, treeNode){
				var dyLayer=this.map.getLayer(treeNode.layerObj.RESOURCE_ID+"#M");
				if(dyLayer){
					this.map.removeLayer(dyLayer);
				}
				var feLayer=this.map.getLayer(treeNode.layerObj.RESOURCE_ID+"#F");
				if(feLayer){
					this.map.removeLayer(feLayer);
				}
				if(this.showLayTreeParents.children.length==0){
					$("#resourceShowedLayerTree").css("display","none");
				}
			},
    		addLayersToMap:function(layerObj){
    			var currentMLayer = null;
    			var currentFLayer = null;
    			if(layerObj.RESOURCE_NAME.indexOf("拓展")!=-1){
    				currentMLayer=this.addDyLayer(layerObj,"TZ");
        			currentFLayer=this.addFeaLayer(layerObj,"TZ");
    			}else if(layerObj.TILEFLAG=="1"){
    				//土规或控规的管理员图层
    				currentMLayer=this.addTKDyLayerForManager(layerObj);
        			currentFLayer=this.addTKFeatureForManager(layerObj);
    			}else{
    				currentMLayer=this.addDyLayer(layerObj);
        			currentFLayer=this.addFeaLayer(layerObj);
    			}
    			var activeMap = this.map;
    			if(Global.maps&&Global.maps.length>0){
    				activeMap = Global.maps.filter(function(item){
    					if(Global.activeMapId.length==0){
    						Global.activeMapId="map";
    						return this.map;
    					}else{
    						return item.id==Global.activeMapId;	
    					}
    				})[0];
    			}
    			//$('#'+Global.activeMapId).showLoading({isModal:false});
    			activeMap.addLayers([currentMLayer,currentFLayer]);
    			
    			if(activeMap.getLevel()>=parseInt(layerObj.CHANGELEVEL)){
    				currentMLayer.hide();
    				currentFLayer.show();
    			}else{
    				currentMLayer.show();
    				currentFLayer.hide();
    			}
    			on(currentFLayer ,"click", lang.hitch(this,function(evt) {
             	   this.queryByLocation(evt)}));
    			if(currentMLayer!=null){
    				on(currentMLayer ,"error", lang.hitch(this,function(evt) {
    					topic.publish("LayerLoadedOrErrorHandler",{id:evt.target.id,loaded:false});
    					//this.layerLoadError(evt.target.id);
    				}));
    				on(currentMLayer ,"load", lang.hitch(this,function(evt) {
    					topic.publish("LayerLoadedOrErrorHandler",{id:evt.target.id,loaded:evt.layer.loaded});
    					//$('#'+Global.activeMapId).hideLoading();
    				}));
    			}
    			if(currentMLayer==null&&currentFLayer!=null){
    				on(currentFLayer ,"error", lang.hitch(this,function(evt) {
    					topic.publish("LayerLoadedOrErrorHandler",{id:evt.target.id,loaded:false});
    					//this.layerLoadError(evt.target.id);
    				}));
    			}
    			
    		},
    		addTKDyLayerForManager:function(layerObj){
    			var tileMaplayer = new ArcGISTiledMapServiceLayer(layerObj.DYNAMICS_URL,{id:layerObj.RESOURCE_ID+"#M"});
    			return tileMaplayer;
    		},
    		addTKFeatureForManager:function(layerObj){
    			var featureLayer=new  FeatureLayer(layerObj.FEATURE_URL+"/"+layerObj.LAYER_INDEX,
    					{id:layerObj.RESOURCE_ID+"#F",
    				     mode: FeatureLayer.MODE_ONDEMAND, 
					     outFields: ["*"],
					     visible:true});
    			return featureLayer;
    		},
    		addDyLayer:function(){
    			var layerObj=arguments[0];
    				try{
        				debugger
        				var dyMaplayer = new ArcGISDynamicMapServiceLayer(layerObj.DYNAMICS_URL,{id:layerObj.RESOURCE_ID+"#M"});
            			var visible=[layerObj.LAYER_INDEX];
            			dyMaplayer.setVisibleLayers(visible);
            			dyMaplayer.attr("lytitle", layerObj.RESOURCE_NAME);
            			var layerDefinetion=[];
            			if(arguments.length==2){
            				var managerUsers=ioc.map.menagerUsers.split(",");
            				managerUsers=skipEmptyElementForArray(managerUsers);
            				var filter =" in (";
            				for(var i=0;i<managerUsers.length;i++){
            					filter += "'"+managerUsers[i]+"'";  
            					if(i<managerUsers.length-1){
            						filter += ",";
            					}}
            				filter += ")";
            				layerDefinetion[layerObj.LAYER_INDEX]="USERNAME"+filter;
            				if(ioc.map.userInfoData.isManager&&ioc.map.userInfoData.isManager==true){
            					layerDefinetion[layerObj.LAYER_INDEX]="1=1";
            				}
            			}else{
            				if(layerObj.FIELDS){
                				layerDefinetion[layerObj.LAYER_INDEX]=layerObj.FIELDS.replace(/%/g,"'");
                			}
            			}
        				dyMaplayer.setLayerDefinitions(layerDefinetion);
            			return dyMaplayer;
        			}catch(e){
        				layer.msg("该专题配置异常",{icon:2});
        				console.log(e);
        			}finally{}
    		},
    		addFeaLayer:function(){
    			var layerObj=arguments[0];
    			try{
    				var featureLayer=new  FeatureLayer(layerObj.FEATURE_URL+"/"+layerObj.LAYER_INDEX,
        					{id:layerObj.RESOURCE_ID+"#F",
        				     mode: FeatureLayer.MODE_ONDEMAND, 
    					     outFields: ["*"],
    					     visible:true});
    				featureLayer.attr("lytitle", layerObj.RESOURCE_NAME);
    				if(arguments.length==2){
    					var managerUsers=ioc.map.menagerUsers.split(",");
        				managerUsers=skipEmptyElementForArray(managerUsers);
        				var filter =" in (";
        				for(var i=0;i<managerUsers.length;i++){
        					filter += "'"+managerUsers[i]+"'";  
        					if(i<managerUsers.length-1){
        						filter += ",";
        					}}
        				filter += ")";
        				featureLayer.setDefinitionExpression("USERNAME"+filter);
        				if(ioc.map.userInfoData.isManager&&ioc.map.userInfoData.isManager==true){
        					featureLayer.setDefinitionExpression("1=1");
        				}
    				}else{
    					if(layerObj.FIELDS){
        					featureLayer.setDefinitionExpression(layerObj.FIELDS.replace(/%/g,"'"))
        				}	
    				}
        			return featureLayer;
    			}catch(e){
    				layer.msg("该专题配置异常",{icon:2});
    				console.log(e);
    			}finally{}
    		},
            destroy: function () {
                var widgets = this.widgets;
                for (var name in widgets) {
                    if (widgets[name]) {
                        widgets[name].destroy();
                    }
                }
                this.inherited(arguments);
            },
      
        });
    });